package com.ly.mpayment.rest.up.fengniu;

import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.Config;
import com.ly.mpayment.core.util.HttpClient;
import com.ly.mpayment.core.util.StringSort;
import com.ly.mpayment.core.util.StringUtils;
import com.ly.mpayment.persist.entity.DownRechargeFlow;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.HashSet;
import java.util.Set;

@Component
@Path("fengniu")
public class FengNiuRest {

    Logger logger = Logger.getLogger(FengNiuRest.class);

    @Autowired
    IUporderService upOrderService;

    @Autowired
    IDownRechargeFlowService flowService;

    @Autowired
    IDownShopInfoService shopService;

    @Autowired
    IUpShopInfoService upShopInfoService;

    @SuppressWarnings("static-access")
    @Path("callBack")
    @POST
    public String callBack(String data) {
        // {
        //     "ordersn":"风云单号",
        //         "extordersn":"合作方单号",
        //         "status":3,
        //         "message":"充值成功",
        //         "timestamp":1609245268,
        //         "sign":"2551d73fe46ea467d2d3d175e992cfae"
        // }
        logger.info("fengniu_callback:" + data);
        if (!StringUtils.isBlank(data)) {
            try{
                JSONObject jsonD = JSONObject.parseObject(data);
                //支付结果 1 成功 2失败
                UpOrder order = upOrderService.findById(jsonD.getString("extordersn"));
                if (order != null && jsonD.getString("status").equals("3") && order.getStatus() == Config.status[0]) {
                    order.setRemark(StringUtils.isBlank(jsonD.getString("voucher")) ? "" : jsonD.getString("voucher"));
                    RechargeRest.successUpOrder.add(order);
                    return "success";
                } else if (order != null && order.getStatus() == Config.status[0] && jsonD.getString("status").equals("4")) {
                    order.setRemark("");
                    RechargeRest.failtUpOrder.add(order);
                    return "success";
                } else {
                    logger.info("fengniu_not_found_order:" + jsonD.getString("extordersn") + "," + order);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return "success";
    }


    /**
     * 订单提交
     *
     * @param order
     * @param shop
     */
    public void commitOrder(UpOrder order, UpShopInfo shop) {
        JSONObject data = new JSONObject();
        data.put("method","recharge");
        data.put("openid",shop.getAppId());
        data.put("appkey",shop.getUpkey());
        data.put("productid",order.getUpShopPro().getProductCode());
        data.put("mobile",order.getUpphonenum());
        data.put("timestamp",order.getCreatetime().getTime() / 1000);
        data.put("callback",shop.getOrderCallAddress());
        data.put("extordersn",order.getUporderuuid());
        data.put("sign", MD5.md5(StringSort.doSign(data).toLowerCase() + shop.getUpshopip()));

        String result = HttpClient.postUrlFrom(shop.getOrderCommitAddress(),"data="+data.toString());
        logger.info("fengniu_result:"+result+","+order.getUpphonenum()+",:"+data.toString());
        try {
            if(!StringUtils.isBlank(result)){
                JSONObject res = JSONObject.parseObject(result);
                //提交成功
                if( res.containsKey("result") && res.getString("result").equals("0")) {
                    upOrderService.updateUpOrderMsg(order, res.getJSONObject("data").getString("ordersn"), res.containsKey("message") ?
                            res.getString("message") : res.getString("result"));
                }else if(res.containsKey("result") && errorCode.contains(res.getString("result"))) {
                    order.setRemark( "");
                    RechargeRest.failtUpOrder.add(order);
                }
            }else{
                upOrderService.updateUpOrderArtificial(order,"","提单异常需要人工");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage());
            upOrderService.updateUpOrderArtificial(order,"","提单异常需要人工");
        }
    }

    // public static void main(String[] args) {
    //     new FengNiuRest().commitOrder(new UpOrder(){{
    //         setUpphonenum("18782435842");
    //         setCreatetime(new Date());
    //         setUpShopPro(new UpShopProduct(){{
    //             setProductCode("xxxx");
    //         }});
    //         setUporderuuid("xxxxx");
    //     }},new UpShopInfo(){{
    //         setOrderCommitAddress("https://data.findnew.com/index/telephone_order/index");
    //         setAppId("5e4131f43746d0ab85a744b7a34d3b2d");
    //         setUpkey("32d492905b52");
    //         setUpshopip("cfec23c6d796");
    //     }});
    // }

    /**
     * -1—失败；
     * 401—参数错误；
     * 402—非法请求；
     * 403—余额不足；
     * 404—扣款失败；
     * 405—签名错误；
     * 406—产品没配置价格；
     * 407—产品已下架
     */
    Set<String> errorCode = new HashSet<String>(){{
        add("-1");
        add("401");
        add("402");
        add("403");
        add("404");
        add("405");
        add("406");
        add("407");
    }};

    /**
     * 订单查询
     * @param upOrder
     * @param shopInfo
     */
    public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {

    }
}
